<template>
  <div>
    <el-card
      class="mt-10"
      shadow="never"
      v-for="(item,index) in checkArr"
      :key="item.moduleCode"
      :body-style="{'padding':'10px 20px'}"
    >
      <div class="d-flex f-align" slot="header">
        <el-checkbox
          :indeterminate="item.isIndeterminate"
          v-model="item.checkedAll"
          @change="(val)=>checkPartAll(val,item)"
        ></el-checkbox>
        <h4 class="ml-10">{{item.moduleName}}</h4>
        <template v-if="item.tips">
          <el-link type="info" :underline="false" icon="el-icon-info" class="fs-16 ml-10 mr-5"></el-link>
          <span class="fs-12">{{item.tips}}</span>
        </template>
      </div>
      <el-checkbox-group
        v-model="item.checked"
        @change="(val)=>handleCheckedChange(val,index,item)"
      >
        <el-checkbox
          v-for="child in item.children"
          :label="child.resourceId"
          :key="child.resourceId"
          class="pt-5 pb-5"
        >{{child.resName}}</el-checkbox>
      </el-checkbox-group>
    </el-card>
  </div>
</template>

<script>
export default {
  props: ["checkArr", "checked"],
  data() {
    return {};
  },
  watch: {
    checkArr: {
      immediate: true,
      handler(val, oldVal) {
        if (val != oldVal) {
          this.getSelected();
        }
      }
    }
  },
  methods: {
    // 全选
    checkPartAll(val, item) {
      let index = this.checkArr.findIndex(o => o.resourceId == item.resourceId);
      let newItem = Object.assign(this.checkArr[index], {
        checked: val ? item.children.map(o => o.resourceId) : [],
        isIndeterminate: false
      });
      this.checkArr.slice(index, 1, newItem);
      this.getSelected();
    },
    handleCheckedChange(val, index, item) {
      item.isIndeterminate =
        val.length > 0 && val.length < item.children.length;
      item.checkedAll = val.length == item.children.length;
      this.$set(this.checkArr, index, item);
      this.getSelected();
    },
    getSelected() {
      let selected = [];
      this.checkArr.forEach(o => {
        selected.push(...o.checked);
      });
      this.$emit("getChecked", selected);
    }
  }
};
</script>
